package com.aita.diamond.service

import com.gd.magic.Service
import com.gd.magic.util.StringUtil
import com.gd.card.constant.CardStatus
import com.gd.card.constant.CardUserStatus

import com.gd.card.mgnt.Card
import com.gd.card.mgnt.CardType
import com.gd.card.constant.CardStoreStatus
import com.gd.card.constant.AccountStatus
import com.gd.domain.party.Organization
 
import org.hibernate.Query

import java.text.*
import com.gd.card.store.CardSpecification
import com.gd.card.constant.BlankCardType
import com.gd.card.constant.StoreOtherConstant

 /**
  * 本类提供发卡充值点柜台业务相关的功能
  * @version V0.2
  * @copyright(c) Copyright G&D Corporation 2007.
  * @author zhanghuanxun
  */
class StoreService implements Service {
			
	public static final String FORMAT_YEARMONTH = "yyyyMM"
	
	def addOrder(){
		
	}
	
	
	def testAddCard(long asn,int cardTypeId,Organization storeLocation){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd")
		Card card = Card.loadByAsn(asn)
		if (card){
			card.asn = -1*System.currentTimeMillis();
			card.terminalId = card.asn % StoreOtherConstant.PSAM_TERMINALID_MOD_NUMBER
			card.merge();
		}
		CardSpecification cardSpec = ejbService.loadByStmt("from CardSpecification as o where o.type=? order by o.createTime asc",BlankCardType.MF1)
		assert cardSpec : X("没有卡片规格！")
		CardType ct = CardType.load(cardTypeId)
		assert ct : X("不是用户卡！")
		card = new Card()
		card.expiredTime = sdf.parse("20101231")
		card.asn = asn
		card.type = ct
		card.foregiftAmount = 0;
		card.baseCardType = ct.baseCardType
		card.status = CardStatus.INITED
		card.storeStatus = CardStoreStatus.STORE
		card.targetOrg = ejbService.loadByStmt("select o from Organization as o where o.orgLevel=200")
		card.cardSpec = cardSpec
		card.storeLocation = storeLocation?storeLocation:loginService.currentOrg()
		card.persist()
		cardStoreService.warehousingForBusiness(card)
		return card
	}
	
	/**
	 *重新启用注销卡
	 */
	def reuseCard(long asn){
		Card card = Card.loadByAsn(asn)
		assert card: X("CARDSEARCH_CARD_WRONG","$asn")
		if (card.status==CardStatus.REVOCATION&&!card.owner.currentCard&&card.owner.status == CardUserStatus.REVOCATION)
		{
			card.owner.status = CardUserStatus.OK
			card.owner.currentCard = card
			card.status = CardStatus.OK

			for (acc in accountService.getCardAccounts(card)){
				accountService.reuseAccount(acc)
			}
			for (acc in accountService.getUserAccounts(card.owner)){
				if (acc.status == AccountStatus.EXPIRED)
					accountService.reuseAccount(acc)
			}
		}
		assert card.status == CardStatus.OK: X("REUSE_CARD_STATUS_WRONG")
		cardStoreService.handleInventoryOnCardStatusChanged(card, CardStatus.REVOCATION, CardStatus.OK)
	}

	
}